package com.dmz.flink;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class StreamWordCount {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStreamSource<String> dataStreamSource = env.readTextFile("E:\\IdeaProjects\\flinkTutorial\\src\\main\\java\\com\\dfjx\\flinkTuorial\\wordCount\\input\\hello.txt");

        /**
         * SingleOutputStreamOperator extend DataStream
         * KeyedStream extend DataStream
         */
        SingleOutputStreamOperator<Tuple2<String, Integer>> dataStreamSourceSum = dataStreamSource.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {

            @Override
            public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                String[] words = value.split(" ");
                for (String word : words) {
                    out.collect(new Tuple2<>(word, 1));
                }
            }
        }).keyBy(0).sum(1);
        dataStreamSourceSum.print("dataStreamSourceSum: ");
        env.execute();
    }
}
